//
//  ConfirmTurnCalendar.m
//  SIqICalendar
//
//  Created by SKiran on 17/3/2.
//  Copyright © 2017年 sjw. All rights reserved.
//

#import "ConfirmTurnCalendar.h"
#import "ConfirmCalendarCollectionViewCell.h"
#import "JWCalendarModel.h"

#define CELL_IDENTIFIER @"ConfirmCalendarCellectionViewCellId"
@interface ConfirmTurnCalendar()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>
@property (nonatomic, strong)UICollectionView  *calendarCollectionView;
@end

@implementation ConfirmTurnCalendar
{
    NSInteger   _lineNumber;// 本月多少行
    NSInteger   _currentMonth;
    NSInteger   _currentYear;
    NSInteger   _turnPeriod;// 周期 / 一个班组多少天
    NSDate      *_turnFirstDate;// 倒班的index==0的起始日期
    UILabel     *_currentDateLabel; // 当前年月
    UIButton    *_preMonthBtn;// 上个月
    UIButton    *_nextMonthBtn;// 下个月
    JWCalendarModel   *_turnModel;
    NSIndexPath  *_selectIndexPath;
}

- (void)drawRect:(CGRect)rect {
    NSLog(@"drawRect: %@",NSStringFromCGRect(rect));
}

- (NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [[NSMutableArray alloc] init];
        
    }
    return _dataSource;
}

- (instancetype)initWithFrame:(CGRect)frame
   withCurrentSelectTurnDatas:(NSMutableArray *)currentAry
                 andTurnModel:(JWCalendarModel *)model
                  andDelegate:(id)delegate {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.currentSelectTurnDatas = currentAry;
        self.delegate = delegate;
        _turnModel = model;
        [self.dataSource addObjectsFromArray:self.currentSelectTurnDatas];
        
        [self initialData];
        
        [self createView];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        
        [self initialData];
        
        [self createView];
    }
    return self;
}

- (void)initialData {
    _lineNumber = 6;
    _currentDate = [NSDate date];// 默认今天
    // 设置当前 年 、月
    [[DateUtil dateUtilShareIntance] setCurrentMonth:&_currentMonth andCurrentYear:&_currentYear withDate:_currentDate];
    _turnPeriod = self.dataSource.count;
    
    if (_turnModel) {
        _turnFirstDate = _turnModel.firstDate;
    }else {
        _turnFirstDate = [NSDate date];
        if ([_delegate respondsToSelector:@selector(didSelectTheFirstDate:)]) {
            [_delegate didSelectTheFirstDate:_turnFirstDate];
        }
    }
    
    
}

- (void)createView {
    
    // 添加星期展示
    CGFloat weekViewHeight = WGiveHeight(30);
    // 当前年月
    _currentDateLabel = [[UILabel alloc]initWithFrame:CGRectZero];
    _currentDateLabel.backgroundColor = [UIColor clearColor];
    _currentDateLabel.textAlignment = NSTextAlignmentCenter;
    _currentDateLabel.textColor = [UIColor whiteColor];
    _currentDateLabel.font = [UIFont boldSystemFontOfSize:CalendarTitleFont];
    [_currentDateLabel setAdjustsFontSizeToFitWidth:YES];
    _currentDateLabel.text = [[DateUtil dateUtilShareIntance] dateToDateStr:_currentDate withFormatter:@"yyyy年M月"];
    [self addSubview:_currentDateLabel];
    
    
    [_currentDateLabel makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(0);
        make.height.equalTo(weekViewHeight);
        make.centerX.equalTo(self.centerX);
    }];
    
    // 上个月
    _preMonthBtn = [[UIButton alloc] initWithFrame:CGRectZero];
    [_preMonthBtn setBackgroundImage:[UIImage imageNamed:@"arror_left"] forState:UIControlStateNormal];
    [_preMonthBtn addTarget:self action:@selector(preMonth) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:_preMonthBtn];
    
    // 下个月
    _nextMonthBtn = [[UIButton alloc] initWithFrame:CGRectZero];
    [_nextMonthBtn setBackgroundImage:[UIImage imageNamed:@"arrow_right"] forState:UIControlStateNormal];
    [_nextMonthBtn addTarget:self action:@selector(nextMonth) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:_nextMonthBtn];
    
    [_preMonthBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_currentDateLabel.left).offset(-15);
        make.centerY.equalTo(_currentDateLabel.centerY);
        make.width.height.equalTo(WGiveHeight(20));
    }];
    
    [_nextMonthBtn makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_currentDateLabel.right).offset(15);
        make.centerY.equalTo(_currentDateLabel.centerY);
        make.width.height.equalTo(WGiveHeight(20));
    }];
    
    UIColor *bgColor = [UIColor colorWithWhite:1.0 alpha:0.8];
    
    UIView *weekView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, weekViewHeight)];
    weekView.backgroundColor = bgColor;
    [self addSubview:weekView];
    
    [weekView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_currentDateLabel.bottom);
        make.left.right.equalTo(0);
        make.height.equalTo(weekViewHeight);
    }];
    
    NSArray *weeks = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    CGFloat weekLabelWidth = weekView.frame.size.width/7.0;
    
    for (int i = 0; i < weeks.count; i++) {
        UILabel *weekLabel = [[UILabel alloc]initWithFrame:CGRectMake(i * weekLabelWidth, 0, weekLabelWidth, weekView.frame.size.height)];
        weekLabel.backgroundColor = [UIColor clearColor];
        weekLabel.textAlignment = NSTextAlignmentCenter;
        weekLabel.textColor = [UIColor lightGrayColor];
        weekLabel.font = [UIFont systemFontOfSize:10];
        [weekLabel setAdjustsFontSizeToFitWidth:YES];
        weekLabel.text = weeks[i];
        [weekView addSubview:weekLabel];
        
    }
    
    //苹果推荐使用的一个标准瀑布流类
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    //内容大小
    flowLayout.itemSize = CGSizeMake((self.frame.size.width)/7, (self.frame.size.height - 6 - weekViewHeight - weekViewHeight) / 6);
    //最小行间距
    flowLayout.minimumLineSpacing = 1;
    //最小列间距
    flowLayout.minimumInteritemSpacing = 0;
    
    // CollectionView Create _____ListView 日历展示
    _calendarCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    _calendarCollectionView.dataSource = self;
    _calendarCollectionView.delegate = self;
    _calendarCollectionView.backgroundColor = bgColor;
    _calendarCollectionView.showsHorizontalScrollIndicator = NO;
    
    [self addSubview:_calendarCollectionView];
    
    [_calendarCollectionView registerClass:[ConfirmCalendarCollectionViewCell class] forCellWithReuseIdentifier:CELL_IDENTIFIER];
    
    [_calendarCollectionView makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(0);
        make.top.equalTo(weekView.bottom);
    }];
    
    [self addSwipeGestureRecognizerOnView:_calendarCollectionView];
}

/**
 *  添加滑动手势
 *
 *  @param view 手势添加到这个视图上
 */
- (void)addSwipeGestureRecognizerOnView:(UIView *)view {
    
    // 手指向左方向滑动
    UISwipeGestureRecognizer *leftswipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(viewSwipe:)];
    leftswipe.direction = UISwipeGestureRecognizerDirectionLeft;
    [view addGestureRecognizer:leftswipe];
    
    // 手指向右方向滑动
    UISwipeGestureRecognizer *rightswipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(viewSwipe:)];
    rightswipe.direction = UISwipeGestureRecognizerDirectionRight;
    [view addGestureRecognizer:rightswipe];
}

/**
 *  滑动手势
 *
 *  @param gesture 手势
 */
- (void)viewSwipe:(UISwipeGestureRecognizer *)gesture {
    
    if (gesture.direction == UISwipeGestureRecognizerDirectionLeft) {
        // 向左滑动 下一个月
        NSLog(@"UISwipeGestureRecognizerDirectionLeft");
        _currentDate = [[DateUtil dateUtilShareIntance] nextMonth:_currentDate];
    }else if (gesture.direction == UISwipeGestureRecognizerDirectionRight ){
        // 向右滑动 上一个月
        NSLog(@"UISwipeGestureRecognizerDirectionRight");
        _currentDate = [[DateUtil dateUtilShareIntance] preMonth:_currentDate];
    }
    
    // 设置当前 年 、月
    [[DateUtil dateUtilShareIntance] setCurrentMonth:&_currentMonth andCurrentYear:&_currentYear withDate:_currentDate];
    
    [_calendarCollectionView reloadData];
    
    // 切换动画
    CATransition *disapperAnim = [CATransition animation];
    disapperAnim.duration = animationDurations;
    disapperAnim.type = @"fade";
    
    [_calendarCollectionView.layer addAnimation:disapperAnim forKey:nil];
    
    _currentDateLabel.text = [[DateUtil dateUtilShareIntance] dateToDateStr:_currentDate withFormatter:@"yyyy年M月"];
}


/**
 按钮点击切换上一个月
 */
- (void)preMonth {
    _currentDate = [[DateUtil dateUtilShareIntance] preMonth:_currentDate];
    // 设置当前 年 、月
    [[DateUtil dateUtilShareIntance] setCurrentMonth:&_currentMonth andCurrentYear:&_currentYear withDate:_currentDate];
    
    [_calendarCollectionView reloadData];
    
    // 切换动画
    CATransition *disapperAnim = [CATransition animation];
    disapperAnim.duration = 0.1;
    disapperAnim.type = @"fade";
    
    [_calendarCollectionView.layer addAnimation:disapperAnim forKey:nil];
    
    _currentDateLabel.text = [[DateUtil dateUtilShareIntance] dateToDateStr:_currentDate withFormatter:@"yyyy年M月"];
}

/**
 按钮点击切换下一个月
 */
- (void)nextMonth {
    _currentDate = [[DateUtil dateUtilShareIntance] nextMonth:_currentDate];
    // 设置当前 年 、月
    [[DateUtil dateUtilShareIntance] setCurrentMonth:&_currentMonth andCurrentYear:&_currentYear withDate:_currentDate];
    
    [_calendarCollectionView reloadData];
    
    // 切换动画
    CATransition *disapperAnim = [CATransition animation];
    disapperAnim.duration = 0.1;
    disapperAnim.type = @"fade";
    
    [_calendarCollectionView.layer addAnimation:disapperAnim forKey:nil];
    
    _currentDateLabel.text = [[DateUtil dateUtilShareIntance] dateToDateStr:_currentDate withFormatter:@"yyyy年M月"];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _lineNumber * 7;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ConfirmCalendarCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELL_IDENTIFIER forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    NSDate *theFirstDay = [[DateUtil dateUtilShareIntance] getTheCalendarFirstDayWithDate:_currentDate];
    // item是纵向递增，根据日历的横向递增；将collectionView的行列对调，根据第一天的时间算出后面的日期
    int row = (int)indexPath.item / 7; // 行
    int column = (int)indexPath.item % 7; // 列
    
    NSInteger oneDayInterval = 24 * 60 * 60;
    NSInteger timeIntervalSinceTheFirstDay = 7 * row * oneDayInterval + column * oneDayInterval; // 7 * row : 第几周   column : 距离本周第一天的时间
    NSInteger theDayIntervalSince1970 = [theFirstDay timeIntervalSince1970] + timeIntervalSinceTheFirstDay;
    
    NSDate *theDate = [NSDate dateWithTimeIntervalSince1970:theDayIntervalSince1970];
    cell.date = theDate;
    
    NSInteger differDaysCount = -1;
    NSInteger theDateInDataSourceIndex = -1;
    if (_turnFirstDate != nil && _turnPeriod > 0) {
        differDaysCount = [[DateUtil dateUtilShareIntance] getDaysFrom:_turnFirstDate To:theDate];// 此日期在倒班日期的或前或后
        theDateInDataSourceIndex = differDaysCount % _turnPeriod;
    }
    
    if (differDaysCount >= 0) {
        cell.dataModel = _dataSource[theDateInDataSourceIndex];
    }else {
        cell.dataModel = nil;
    }
    
    if ([[[DateUtil dateUtilShareIntance] dateToDateStr:_turnFirstDate] isEqualToString:[[DateUtil dateUtilShareIntance] dateToDateStr:theDate]]) {
        cell.selectImageView.hidden = NO;
    }else {
        cell.selectImageView.hidden = YES;
    }
    
    if ([[[DateUtil dateUtilShareIntance] getComps:theDate] month] == _currentMonth && [[[DateUtil dateUtilShareIntance] getComps:theDate] year] == _currentYear) {
        cell.dateTextLabel.textColor = [UIColor blackColor];
        cell.dateTextLabel.text = [[DateUtil dateUtilShareIntance] dateToMonthDayStr:theDate];
        // 圈中今天
        if ([[[DateUtil dateUtilShareIntance] dateToDateStr:theDate] isEqualToString:[[DateUtil dateUtilShareIntance] dateToDateStr:[NSDate date]]]) {
            cell.todayClickImageView.hidden = NO;
        }else {
            cell.todayClickImageView.hidden = YES;
        }
    }else {
        cell.dateTextLabel.textColor = [UIColor lightGrayColor];
        cell.dateTextLabel.text = [[DateUtil dateUtilShareIntance] dateToMonthDayStr:theDate];
    }
    
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    ConfirmCalendarCollectionViewCell *cell = (ConfirmCalendarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    NSLog(@"%@",cell.date);
    _turnFirstDate = cell.date;
    // 设置倒班周期
    if (self.dataSource.count > 0) {
        _turnPeriod = self.dataSource.count;
    }
    
    if ([_delegate respondsToSelector:@selector(didSelectTheFirstDate:)]) {
        [_delegate didSelectTheFirstDate:_turnFirstDate];
    }
    
    [collectionView reloadData];
}

#pragma mark - set
- (void)setCurrentDate:(NSDate *)currentDate {
    _currentDate = currentDate;
    // 设置当前 年 、月
    [[DateUtil dateUtilShareIntance] setCurrentMonth:&_currentMonth andCurrentYear:&_currentYear withDate:_currentDate];
    
    [_calendarCollectionView reloadData];
}


@end
